<template>
  <div style="width: 60%; margin: 50px auto" class="card">
    <el-descriptions title="个人信息" border :column="2" style="margin-bottom: 20px">
      <el-descriptions-item label="头像" align="center">
        <el-upload
            :action="baseUrl + '/files/upload'"
            :on-success="handleFileUpload"
            :show-file-list="false"
            class="avatar-uploader"
        >
          <img v-if="data.user.avatar" :src="data.user.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-descriptions-item>
      <el-descriptions-item label="用户名" align="center">
        <span>{{ data.user.username }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="姓名" align="center">
        <span>{{ data.user.name }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="电话" align="center">
        <span>{{ data.user.phone || '未填写' }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="邮箱" align="center">
        <span>{{ data.user.email || '未填写' }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="操作" align="center">
        <el-button type="warning" @click="updateInit">修改密码</el-button>
        <el-button type="primary" @click="editMode = true">编辑信息</el-button>
      </el-descriptions-item>
    </el-descriptions>

    <!-- 编辑模式 -->
    <el-form v-if="editMode" ref="userForm" :model="data.tempUser" label-width="100px" style="padding: 20px">
      <el-form-item prop="name" label="姓名">
        <el-input v-model="data.tempUser.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="电话">
        <el-input v-model="data.tempUser.phone" placeholder="请输入电话"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="data.tempUser.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <div style="text-align: center">
        <el-button type="primary" @click="updateUserInfo">保 存</el-button>
        <el-button @click="cancelEdit">取消</el-button>
      </div>
    </el-form>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.passwordData" label-width="70px" style="padding: 20px">
        <el-form-item label="原密码" prop="password">
          <el-input v-model="data.passwordData.password" placeholder="请输入原密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="data.passwordData.newPassword" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="data.passwordData.confirmPassword" placeholder="请确认新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelPasswordUpdate">取 消</el-button>
          <el-button type="primary" @click="savePassword">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import router from "@/router/index.js";
import { Plus } from "@element-plus/icons-vue";

const formRef = ref();
const baseUrl = import.meta.env.VITE_BASE_URL;
const editMode = ref(false);

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else if (value !== data.passwordData.newPassword) {
    callback(new Error("确认密码跟新密码不一致!"));
  } else {
    callback();
  }
};

const data = reactive({
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  tempUser: {
    name: '',
    phone: '',
    email: ''
  },
  formVisible: false,
  passwordData: {
    password: '',
    newPassword: '',
    confirmPassword: ''
  },
  rules: {
    password: [
      { required: true, message: '请输入原密码', trigger: 'blur' },
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
    ],
    confirmPassword: [
      { validator: validatePass, trigger: 'blur' }
    ]
  }
});

// 初始化临时用户数据
data.tempUser.name = data.user.name;
data.tempUser.phone = data.user.phone;
data.tempUser.email = data.user.email;

const fetchUserInfo = () => {
  request.get('/user/getUserInfo').then(res => {
    if (res.code === '200') {
      data.user = res.data; // 更新用户信息
      data.tempUser.name = res.data.name; // 初始化临时用户数据
      data.tempUser.phone = res.data.phone;
      data.tempUser.email = res.data.email;
      localStorage.setItem('user', JSON.stringify(res.data)); // 更新本地缓存
      localStorage.setItem('token', res.data.token); // 更新 token
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(error => {
    ElMessage.error('获取用户信息失败，请稍后重试');
    console.error(error);
  });
};

onMounted(() => {
  fetchUserInfo(); // 在组件加载时获取用户信息
});

const handleFileUpload = (res) => {
  data.user.avatar = res.data;
  update(); // 更新用户信息以保存新的头像
};

const update = () => {
  if (data.user.role === 'USER') {
    request.put('/user/update', data.user).then(res => {
      if (res.code === '200') {
        ElMessage.success('保存成功');
        localStorage.setItem('user', JSON.stringify(data.user));
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

const updateInit = () => {
  data.formVisible = true;
  // 清空密码表单数据
  data.passwordData.password = '';
  data.passwordData.newPassword = '';
  data.passwordData.confirmPassword = '';
};

const cancelPasswordUpdate = () => {
  data.formVisible = false;
  // 清空密码表单数据
  data.passwordData.password = '';
  data.passwordData.newPassword = '';
  data.passwordData.confirmPassword = '';
};

const savePassword = () => {
  formRef.value.validate(valid => {
    if (valid) {
      request.put('/updatePassword', {
        userId: data.user.id,
        password: data.passwordData.password,
        newPassword: data.passwordData.newPassword
      }).then(res => {
        if (res.code === '200') {
          localStorage.removeItem('user');
          localStorage.removeItem('token');
          router.push('/login');
          ElMessage.success('密码修改成功');
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};

const updateUserInfo = () => {
  data.user.name = data.tempUser.name;
  data.user.phone = data.tempUser.phone;
  data.user.email = data.tempUser.email;

  request.put('/user/update', data.user).then(res => {
    if (res.code === '200') {
      ElMessage.success('保存成功');
      localStorage.setItem('user', JSON.stringify(data.user)); // 更新本地缓存
      editMode.value = false; // 关闭编辑模式
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(error => {
    console.error(error);
    ElMessage.error('更新用户信息失败，请稍后重试');
  });
};

const cancelEdit = () => {
  editMode.value = false;
  // 重置临时用户数据为原始用户数据
  data.tempUser.name = data.user.name;
  data.tempUser.phone = data.user.phone;
  data.tempUser.email = data.user.email;
};
</script>

<style scoped>
.card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 20px;
  background-color: #fff;
}

.avatar-uploader {
  height: 120px;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border-radius: 50%;
}
</style>
